package com.test.cn.game

import scala.io.StdIn

class Game {

  //决出胜负是有限的
  /*     1       2      3
        石头    剪子    布
1 石头  (1,1) (2,0) (0,2)
2 剪子  (0,2) (1,1) (2,0)
3 布    (2,0) (0,2) (1,1)
    */
  val winMap: Map[(Int, Int), (Int, Int, String)] = Map(
    (1, 1) -> (1, 1, "平局"), (1, 2) -> (2, 0, "你赢了"), (1, 3) -> (0, 2, "你输了"),
    (2, 1) -> (0, 2, "你输了"), (2, 2) -> (1, 1, "平局"), (2, 3) -> (2, 0, "你赢了"),
    (3, 1) -> (2, 0, "你赢了"), (3, 2) -> (0, 2, "你输了"), (3, 3) -> (1, 1, "平局"))

  var roleMap = Map(1 -> "刘备", 2 -> "关羽", 3 -> "张飞")

  //一次战斗
  def oneGame(user: User, computer: Computer): Unit = {
    try {
      val x = user.showFist
      val y = computer.showFist
      val tuple3 = winMap.get((x, y)).get
      println(s"结果：${tuple3._3}")

      user.score += tuple3._1
      computer.score += tuple3._2

      tuple3._3 match {
        case "平局" => user.peace += 1; computer.peace += 1
        case "你赢了" => user.win += 1; computer.fault += 1
        case "你输了" => user.fault += 1; computer.win += 1
      }
    } catch {
      case _ =>
        println("输入不规范，重新输入!")
        oneGame(user, computer)
        return
    }


  }

  //开始
  def begin: Unit = {
    println("猜拳开始")
    println("请选择对战角色(1,刘备 2.关羽 3.张飞)")
    val select = StdIn.readInt()
    val maybeString = roleMap.get(select)
    val success = maybeString match {
      case Some(_) => {
        println(s"你选择了${maybeString.get}对战")
        1
      }
      case None => {
        println("输入错误，退出程序")
        -1
      }
    }
    if (success == -1) {
      return
    }


    //创建用户
    val user = new User("游客")
    val computer: Computer = new Computer(maybeString.get)

    var flag = true
    var count = 0
    while (flag) {
      println("要开始么(y/n)？")
      val str = StdIn.readLine()
      str match {
        case "y" => {
          count += 1
          oneGame(user, computer)
        }
        case "n" => {
          println("退出游戏！")
          flag = false
        }
        case _ => println("输入错误重新输入！")
      }
    }
    //打印成绩
    printScore(user, computer, count)


  }


  private def printScore(user: User, computer: Computer, count: Int)

  = {
    //打印成绩
    println("==================")
    println(s"${computer name} VS ${user name}")
    println(s"对战次数:${count}")
    println(s"姓名\t\t得分\t\t胜局\t\t和局\t\t负局")
    println(s"${computer name}\t\t${computer.score}\t\t${computer.win}\t\t${computer.peace}\t\t${computer.fault}")
    println(s"${user name}\t\t${user.score}\t\t${user.win}\t\t${user.peace}\t\t${user.fault}")
  }

}

object Game {
  def main(args: Array[String]): Unit = {
    val game = new Game
    game.begin

  }
}